package com.thprojects.myphotomemories.view.components;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.LinearLayout;

import com.thprojects.myphotomemories.R;
import com.thprojects.myphotomemories.controller.GuiController;
import com.thprojects.myphotomemories.model.Album;

public class AlbumPreviewList extends LinearLayout{
	
	List<Album> mAlbums;
	int mSelectedIdx = -1;
	
	List<Dot> mDots = new ArrayList<Dot>();
	Context mContext;
	LinearLayout mPreviewContainer;
	LinearLayout mDotsContainer;
	
	Gallery mGallery;

	
	public AlbumPreviewList(List<Album> albums, Context context){
		super(context);
		
		mAlbums = albums;
		mContext = context;
		
		
		//load layout
		LayoutInflater inflater = (LayoutInflater)((context).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
		inflater.inflate(R.layout.album_preview_list, this);
		
		mPreviewContainer = (LinearLayout)findViewById(R.id.preview_container);
		mDotsContainer = (LinearLayout)findViewById(R.id.dots_container);
		
		mGallery = (Gallery)findViewById(R.id.album_gallery);
		mGallery.setAdapter(new AlbumAdapter(mAlbums, mContext));
		mGallery.setSpacing(0);
		mGallery.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	            openAlbum(mAlbums.get(position));
	        }
	    });
		
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				select(arg2);
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				select(0);
			}
			
		});
		
		//draw the dots
		LinearLayout.LayoutParams l = new LinearLayout.LayoutParams(25, 25);
		l.setMargins(10, 10, 10, 10);
		
		for (int i=0; i<mAlbums.size(); i++){			
			Dot d = new Dot(i, context);
			mDotsContainer.addView(d, l);
			mDots.add(d);
			d.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					select(((Dot)v).getIndex());
				}
			});
		}	
		
		select(0);
	}
	
	
	private void select(int idx){
		Log.d("MPM", "selected: "+idx);
		if (idx == mSelectedIdx) return;
		
		if (mSelectedIdx != -1){
			mDots.get(mSelectedIdx).turnOff();
		}
		mSelectedIdx = idx;
		
		mGallery.setSelection(idx);
		
		mDots.get(mSelectedIdx).turnOn();
	}
	

	private void openAlbum(Album a){
		Log.d("MPM", "opening "+a.getName());
		GuiController.showAlbum(mContext, a);
	}
	
}
